package ihm.panel.file;

import ihm.applet.KrakenApplet;
import ihm.panel.PanelInterface;

import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.hibernate.Session;

import tools.AppletConstant;

import enumTypes.LogType;

import bdd.sql.server.bean.Log;
import bdd.sql.server.bean.User;
import bdd.sql.server.bean.User_Log;

/**
 * Affiche la page d'accueil de l'applet.
 * @author Guillaume Pocas & Jean-François Augé
 */
public class WelcomePanel extends JPanel implements ActionListener, PanelInterface {

	private static final long serialVersionUID = 1L;
	private JLabel welcome_jl, alert_jl;
	private JButton disconnect_jb;
	
	private KrakenApplet applet;
	
	/**
	 * Constructeur.
	 * @param applet
	 */
	public WelcomePanel(KrakenApplet applet) {
		this.applet = applet;
		initPanel();
	}

	@Override
	public void initPanel() {
		setLayout(new GridBagLayout());
		GridBagConstraints constraints = new GridBagConstraints();
		
		constraints.insets = new Insets(AppletConstant.BUTTON_INSET,
				AppletConstant.BUTTON_INSET,
				AppletConstant.BUTTON_INSET,
				AppletConstant.BUTTON_INSET);

		constraints.gridx = 0;
		constraints.gridy = 0;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		constraints.anchor = GridBagConstraints.WEST;
		constraints.fill = GridBagConstraints.NONE;
		
		welcome_jl = new JLabel("");
		add(welcome_jl, constraints);

		constraints.gridy++;
		alert_jl = new JLabel("");
		add(alert_jl, constraints);

		constraints.gridy++;
		disconnect_jb = new JButton("Déconnexion");
		disconnect_jb.addActionListener(this);
		add(disconnect_jb, constraints);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource().equals(disconnect_jb)) {
			applet.disconnect();
		}
	}
	
	@Override
    public void paintComponent(Graphics g) {
		Session session = applet.getSession();

		int alerts = 0;
		@SuppressWarnings("unchecked")
		List<Log> resultats = session.createCriteria(Log.class).list();
		for(Log l : resultats)
			// TODO vérifier que ca marche
			if(l.getLog_type_importance().equals(LogType.Alert))
				alerts++;
		
		User user = (User) session.load(User.class, applet.getUser_ID());
		welcome_jl.setText("Bienvenue "+user.getUser_civil()+" "+user.getUser_lastname()+"!");
		
		for(User_Log l : user.getUser_logs())
			if(l.isUser_log_read() == 1)
				alerts--;
		
		if(alerts == 1)
			alert_jl.setText("Vous avez alerte "+alerts+" non lue!");
		else
			alert_jl.setText("Vous avez alertes "+alerts+" non lues!");
		
		session.close();
        super.paintComponent(g);
    }

}
